package com.qiangesoft.design.structural.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib动态代理
 */
public class CglibDynamicProxy {
    public static void main(String[] args) {
        RealDriver realDriver = new RealDriver();
        ProxyDriver proxyDriver = new ProxyDriver(realDriver);
        RealDriver proxy = (RealDriver) proxyDriver.getProxyInstance();
        proxy.drive("奥迪A6L");
    }
}

/**
 * 驾驶员接口
 */
interface Driver {
    void drive(String car);
}

/**
 * 真实驾驶员
 */
class RealDriver implements Driver {

    @Override
    public void drive(String car) {
        System.out.println("【" + car + "】被开回家了");
    }
}

/**
 * 代理驾驶员
 */
class ProxyDriver implements MethodInterceptor {
    private Object realDriver;

    public ProxyDriver(Object realDriver) {
        this.realDriver = realDriver;
    }

    public Object getProxyInstance() {
        // 1.工具类
        Enhancer enhancer = new Enhancer();
        // 2.设置父类
        enhancer.setSuperclass(realDriver.getClass());
        // 3.设置回调函数
        enhancer.setCallback(this);
        // 4.创建子类（代理对象）
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("代驾取钥匙");

        Object result = method.invoke(realDriver, args);

        System.out.println("代驾还钥匙");
        return result;
    }
}